package tests;

import static org.junit.Assert.fail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterTest;

import com.opera.core.systems.OperaDriver;

public class TestBase {
	
	
	@AfterTest
	public void tearDown() throws Exception {
		stop();
	}
	
	protected WebDriver driver;
	protected StringBuffer verificationErrors = new StringBuffer();
	InputStream stream = null;
	InputStreamReader reader = null;
	protected Properties props = new Properties();
	private String configFile;
	
	protected TestBase() {	
		if (configFile == null) {
			configFile = "appProperties";
		}
		InputStream stream;
		try {
			stream = new FileInputStream(new File(configFile));
			reader = new InputStreamReader(stream,"UTF-8");
			props.load(reader);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		String browser = props.getProperty("browser", "firefox");
		
		if (driver == null) {
			driver = getDriver(browser);
			driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
		}
	}	
	

	protected WebDriver getDriver(String browser) {

		if ("firefox".equals(browser)) {
			driver = new FirefoxDriver();
		} else if ("ie".equals(browser)) {
			driver = new InternetExplorerDriver();
		} else if ("chrome".equals(browser)) {
			driver = new ChromeDriver();
		} else if ("opera".equals(browser)) {
			driver = new OperaDriver();		
		}
		return driver;
		
	}
	
	
	
	
	protected WebDriver stop() {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
		return driver;
		
	}
	
	protected void logIn() {
		openBaseUrl();
		fillArea(By.id("username"), "admin");
		fillArea(By.name("password"), "admin");
		click(By.name("submit"));
		
	}
	
	protected void logOut() {
		click(By.linkText("Log out"));
		driver.switchTo().alert().accept();
	}
	
	private void click(By by) {
		driver.findElement(by).click();
	}

	private void fillArea(By by, String name) {
		driver.findElement(by).clear();
		driver.findElement(by).sendKeys(name);
	}

	private void openBaseUrl() {
		driver.get("http://localhost/php4dvd/");
	}
	
	
}
